// 设置 webpack public path，qiankun 必需配置
if (window.__POWERED_BY_QIANKUN__) {
  __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}

import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import "@/assets/css/index.less";

import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
// import "./utils/micro-element-fix.js"
import XLSX from "xlsx";
import FileSaver from "file-saver";
import VuePreview from "vue-preview";
import Viewer from "v-viewer";

import "viewerjs/dist/viewer.css";
import moment from "moment";
Vue.prototype.$moment = moment;
// import scroll from "vue-seamless-scroll";
// Vue.use(scroll);

Vue.config.productionTip = false;
// 使用element
Vue.use(ElementUI);
Vue.use(Viewer, {
  defaultOptions: {
    zIndex: 9999, // 设置图片预览组件的层级，确保能在其他组件之上
  },
});

let instance = null;

// 添加全局路由守卫，修复history.state.current问题
router.beforeEach((to, from, next) => {
  // 确保history.state.current被正确设置
  if (window.history.state && !window.history.state.current) {
    const newState = { ...window.history.state, current: to.fullPath };
    window.history.replaceState(newState, "", window.location.href);
  }
  next();
});

// 渲染函数
function render(props = {}) {
  const { container, routerBase, currentPath, route } = props;

  instance = new Vue({
    router,
    store,
    render: (h) => h(App),
  }).$mount(container ? container.querySelector("#app") : "#app");

  // 如果是微应用模式且有路由信息，进行路由跳转
  if (window.__POWERED_BY_QIANKUN__ && currentPath) {
    console.log("🔀 微应用路由跳转:", currentPath);
    instance.$nextTick(() => {
      router.push(currentPath).catch((err) => {
        console.log("路由跳转:", err.message);
      });
    });
  }
}

// 独立运行时
if (!window.__POWERED_BY_QIANKUN__) {
  render();
}

// qiankun生命周期钩子 - 微应用挂载前
export async function bootstrap() {
  console.log("✅ [BMS] 微应用 bootstrap");
}

// qiankun生命周期钩子 - 微应用挂载后
export async function mount(props) {
  console.log("✅ [BMS] 微应用 mount", props);
  render(props);
}

// qiankun生命周期钩子 - 微应用卸载
export async function unmount() {
  console.log("✅ [BMS] 微应用 unmount");
  instance.$destroy();
  instance.$el.innerHTML = "";
  instance = null;
}
